package com.zxh.blog.activity

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.Toast
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.gyf.immersionbar.ImmersionBar
import com.zxh.blog.R
import com.zxh.blog.bean.ResponseJson
import com.zxh.blog.bean.UserInfo
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okio.IOException

class RegisterActivity : AppCompatActivity() {

    // 用户名
    private lateinit var etUsername: EditText
    // 昵称
    private lateinit var etNickname: EditText
    // 邮箱
    private lateinit var etEmail: EditText
    // 密码
    private lateinit var etPassword: EditText
    // 确认密码
    private lateinit var etConfirmPassword: EditText
    // 注册按钮
    private lateinit var btnRegister: Button
    // 退出按钮
    private lateinit var btnBack: ImageButton

    private var username = ""
    private var nickname = ""
    private var email = ""
    private var password = ""
    private var confirmPass = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)

        ImmersionBar.with(this)
            .statusBarColor(R.color.app_back)
            .statusBarDarkFont(true)
            .fitsSystemWindows(true)
            .init()

        // 初始化控件
        etUsername = findViewById(R.id.etUsername)
        etNickname = findViewById(R.id.etNickname)
        etEmail = findViewById(R.id.etEmail)
        etPassword = findViewById(R.id.etPassword)
        etConfirmPassword = findViewById(R.id.etConfirmPassword)
        btnRegister = findViewById(R.id.btnRegister)
        btnBack = findViewById(R.id.btn_back)

        // 点击注册按钮
        btnRegister.setOnClickListener {
            username = etUsername.text.toString()
            nickname = etNickname.text.toString()
            email = etEmail.text.toString()
            password = etPassword.text.toString()
            confirmPass = etConfirmPassword.text.toString()
            var registerFlag = true
            if (username.isEmpty()) {
                registerFlag = false
                Toast.makeText(this,"用户名不能为空！！！",Toast.LENGTH_SHORT).show()
            }
            if (nickname.isEmpty()) {
                registerFlag = false
                Toast.makeText(this,"昵称不能为空！！！",Toast.LENGTH_SHORT).show()
            }
            if (email.isEmpty()) {
                registerFlag = false
                Toast.makeText(this,"邮箱不能为空！！！",Toast.LENGTH_SHORT).show()
            }
            if (password.isEmpty()) {
                registerFlag = false
                Toast.makeText(this,"密码不能为空！！！",Toast.LENGTH_SHORT).show()
            }
            if (confirmPass.isEmpty()) {
                registerFlag = false
                Toast.makeText(this,"确认密码不能为空！！！",Toast.LENGTH_SHORT).show()
            }
            if (password != confirmPass) {
                registerFlag = false
                Toast.makeText(this,"两次密码不相同，请重新输入！！！",Toast.LENGTH_SHORT).show()
            }
            if (registerFlag) {
                registerByOkhttp(this)
            }
        }

        // 点击退出按钮
        btnBack.setOnClickListener {
            // 销毁页面
            finish()
        }


    }

    private fun registerByOkhttp(context: Context) {
        val mJSON = "application/json;charset=UTF-8".toMediaType()
        val client = OkHttpClient()
        val url = "http://43.140.201.43:7777/user/register"
        val map = mutableMapOf<String, String>()
        map["username"] = username
        map["password"] = password
        map["nickname"] = nickname
        map["email"] = email
        val json = Gson().toJson(map)

        // 创建JSON格式的请求体
        val jsonRequestBody = json.toRequestBody(mJSON)

        // 创建POST请求
        val request = Request.Builder()
            .url(url)
            .post(jsonRequestBody)
            .build()

        // 发送请求
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                // 请求失败处理
                e.printStackTrace()
            }

            override fun onResponse(call: Call, response: Response) {
                // 获取响应结果
                val responseBody = response.body?.string()

                // 处理响应结果
                if (response.isSuccessful) {
                    // 请求成功，处理登录成功逻辑
                    // 可以通过responseBody解析服务器返回的数据
                    if (responseBody != null) {
                        val responseJson = parseJSONWithGSON(responseBody)
                        if (responseJson.code == 200) {
                            runOnUiThread {
                                Toast.makeText(context, "注册成功", Toast.LENGTH_SHORT).show()
                            }
                            startActivity(Intent(context, LoginActivity::class.java))
                            finish()
                        } else {
                            val msg = responseJson.msg
                            runOnUiThread {
                                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                            }
                        }
                    }
                } else {
                    // 请求失败，处理登录失败逻辑
                    runOnUiThread {
                        Toast.makeText(context, "系统异常", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })
    }

    private fun parseJSONWithGSON(responseBody: String): ResponseJson<UserInfo> {
        val gson = Gson()
        val typeToken = object : TypeToken<ResponseJson<UserInfo>>() {}.type
        return gson.fromJson(responseBody, typeToken)
    }


}